<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class DealGoodCacheComponent extends Component
{

    public $_cache_config = 'deal_goods';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 获取优惠信息id
     */
    public function getVal($good_id)
    {
        $key = 'good_' . $good_id;
        $data = Cache::read($key, $this->_cache_config);
        return empty($data) ? $this->createCache($good_id) : $data;
    }

    /**
     * 创建优惠缓存
     */
    public function createCache($good_id)
    {
        $key = 'good_' . $good_id;
        $controller = $this->_registry->getController();
        $controller->loadModel('DealGoods');
        $data = $controller->DealGoods->find()
            ->where(['good_id' => $good_id])
            ->toArray();
        if(!empty($data)){
            foreach ($data as $k=>$v){
                $cache[] = $v['deal_type'].'_'.$v['deal_id'];
            }
        }else{
            $cache = null;
        }
        Cache::write($key, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 删除缓存
     */
    public function deleteCache($good_id)
    {
        $key = 'good_' . $good_id;
        Cache::delete($key, $this->_cache_config);
        return true;
    }

}